package com.nf.health.app.activity.ecg;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.ecgmonitorhd.ecglib.model.EcgAnalyzeResponse;
import com.ecgmonitorhd.ecglib.model.InstitBean;
import com.ecgmonitorhd.ecglib.ui.EcgActivity;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.github.jdsjlzx.util.RecyclerViewStateUtils;
import com.github.jdsjlzx.view.LoadingFooter;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.adapter.EcgHitoryListAdapter;
import com.nf.health.app.customview.CircleImageView;
import com.nf.health.app.customview.DividerListItemDecoration;
import com.nf.health.app.http.Act;
import com.nf.health.app.http.ImageUpLoader;
import com.nf.health.app.models.EcgHistory;
import com.nf.health.app.models.UserInfo;
import com.nf.health.app.utils.Base64Util;
import com.nf.health.app.utils.DataCleanManager;
import com.nf.health.app.utils.DensityUtil;
import com.nf.health.app.utils.GetToast;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ViewUtil;
import com.nf.health.app.widget.MyMainItemAnimation;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by fei on 2016/11/7.
 */
public class EcgHistoryActivity extends BaseActivity {
    private static final String TAG = "EcgHistoryActivity";
    @Bind(R.id.rcl_ecg_mian)
    LRecyclerView rcl_ecg_mian;
    @Bind(R.id.titlebar_right_tv)
    TextView  titlebar_right_tv;
    @Bind(R.id.iv_measure_ecg)
    CircleImageView iv_measure_ecg;
    private int  pageNo = 1 ;
    private int pageSize = 10;
    private   List<EcgHistory> ecglist;
    private EcgHitoryListAdapter ecgHitoryListAdapter;
    private LRecyclerViewAdapter mLRecyclerViewAdapter  = null;;
    private int delIndex = -1;
    private boolean isCanLoadmore =  false;
    private  ImageUpLoader upLoader;
    private String toOrigonalData [] = new String[2];
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_ecghistory);//汗液数据 layout布局
        ButterKnife.bind(this);
        ViewUtil.setText(this, R.id.titlebar_title_tv, "历史记录");
        ViewUtil.setText(this, R.id.titlebar_right_tv, "编辑");
        initListener();
        initData();
        pageNo  = 1;
        loadData(Act.Flag.FLAG_REFRESH_DATA);
    }
    private void initData() {
        //发图片后提交文字
        upLoader = new ImageUpLoader(EcgHistoryActivity.this, EcgHistoryActivity.this);
        titlebar_right_tv.setVisibility(View.VISIBLE);
        titlebar_right_tv.setOnClickListener(this);
        iv_measure_ecg.setOnClickListener(this);
        rcl_ecg_mian.setItemAnimator(new MyMainItemAnimation());
        rcl_ecg_mian.setLayoutManager(new LinearLayoutManager(this));
        rcl_ecg_mian.addItemDecoration(new DividerListItemDecoration(EcgHistoryActivity.this, LinearLayoutManager.VERTICAL, 20,
                getResources().getColor(R.color.divider_line_color)));
        rcl_ecg_mian.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        rcl_ecg_mian.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        iv_measure_ecg.setDrawText("去测量");
        iv_measure_ecg.setDrawTextSize(DensityUtil.sp2px(EcgHistoryActivity.this,12));
        iv_measure_ecg.setDrawTextColorResourse(R.color.white);
       // rcl_ecg_mian.addHeaderView(new SampleHeader(this));

        ecglist = new ArrayList<>();
        /*ecgHitoryListAdapter = new EcgHitoryListAdapter(EcgHistoryActivity.this,ecglist);
        rcl_ecg_mian.setAdapter(ecgHitoryListAdapter);*/
        rcl_ecg_mian.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                titlebar_right_tv.setText("编辑");
                RecyclerViewStateUtils.setFooterViewState(rcl_ecg_mian, LoadingFooter.State.Normal);
                pageNo  = 1;
                loadData(Act.Flag.FLAG_REFRESH_DATA);
            }
        });
        rcl_ecg_mian.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                titlebar_right_tv.setText("编辑");
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(rcl_ecg_mian);
                if(state == LoadingFooter.State.Loading) {
                    return;
                }
                if(isCanLoadmore){
                    pageNo ++;
                    loadData(Act.Flag.FLAG_LOAD_MODE_DATA);
                    RecyclerViewStateUtils.setFooterViewState(EcgHistoryActivity.this, rcl_ecg_mian, pageSize, LoadingFooter.State.Loading, null);
                }else{
                    RecyclerViewStateUtils.setFooterViewState(EcgHistoryActivity.this, rcl_ecg_mian, pageSize, LoadingFooter.State.TheEnd, null);
                }
            }
        });
        rcl_ecg_mian.setLScrollListener(new LRecyclerView.LScrollListener() {
            @Override
            public void onScrollUp() {
            }
            @Override
            public void onScrollDown() {
            }
            @Override
            public void onScrolled(int distanceX, int distanceY) {
            }
            @Override
            public void onScrollStateChanged(int state) {
            }

        });

    }
    public void loadData(String httpFlag){
        provider.getEcgHistory(String.valueOf(pageNo),String.valueOf(pageSize),httpFlag);
    }
    @Override
    public void handleActionStart(String actionName, Object object) {
        super.handleActionStart(actionName, object);
       // hideLoading();
    }

    @Override
    public void handleActionFinish(String actionName, Object object) {
        super.handleActionFinish(actionName, object);
        delIndex = -1;
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        switch (actionName){
            case  Act.Flag.FLAG_REFRESH_DATA://下拉刷新列表
                ecglist.clear();
                rcl_ecg_mian.refreshComplete();
                List<EcgHistory> list = (List<EcgHistory>) object;
                if(list != null){
                    ecglist.addAll(list);
                    if(ecgHitoryListAdapter == null){
                        ecgHitoryListAdapter = new EcgHitoryListAdapter(EcgHistoryActivity.this,ecglist);
                        mLRecyclerViewAdapter = new LRecyclerViewAdapter(ecgHitoryListAdapter);
                        rcl_ecg_mian.setAdapter(mLRecyclerViewAdapter);
                    }else{
                        mLRecyclerViewAdapter.notifyDataSetChanged();
                    }
                    ecgHitoryListAdapter.setOnItemClickLitener(new EcgHitoryListAdapter.OnItemDelClickListener() {
                        @Override
                        public void onItemClick(int position) {
                            delIndex = position;
                            provider.delHistoryById(Constants.TYPE_ECG,ecglist.get(position).getId()+"",Constants.TYPE_ECG);
                        }
                    });
                    if(list.size() < pageSize){//说明加载完毕
                        rcl_ecg_mian.setNoMore(true);
                        isCanLoadmore = false;
                    }else{
                        rcl_ecg_mian.setNoMore(false);
                        isCanLoadmore = true;
                    }
                }
                break;
            case  Act.Flag.FLAG_LOAD_MODE_DATA:////上拉加载更多
                for (int i = 0; i < ecglist.size(); i++) {
                    ecglist.get(i).setEditStatus(false);
                }
                rcl_ecg_mian.refreshComplete();
                List<EcgHistory> subList = (List<EcgHistory>) object;
                ecglist.addAll(subList);
                mLRecyclerViewAdapter.notifyDataSetChanged();
                if(subList.size() < pageSize){//说明加载完毕
                    rcl_ecg_mian.setNoMore(true);
                    isCanLoadmore = false;
                }else{
                    rcl_ecg_mian.setNoMore(false);
                    isCanLoadmore = true;
                }

                RecyclerViewStateUtils.setFooterViewState(rcl_ecg_mian, LoadingFooter.State.Normal);
                break;
            case  Constants.TYPE_ECG://删除历史记录
                if(delIndex >-1) ecglist.remove(delIndex);
                ecgHitoryListAdapter.setEcgHitoryListAdapterDataChanged(ecglist);
                break;
            case ImageUpLoader.FLAG://图片上传成功
                String picUrl = object.toString();
                //GetToast.useString(EcgHistoryActivity.this, "上传图片：    "+object.toString());
                try {
                    String ptype = String.valueOf(2);
                    //文件的本地路径
                    String localPath = toOrigonalData[0];
                    String reportEcgFilePath = localPath.replace("png", "ecg");
                    byte[] ecgResult  = readStream(reportEcgFilePath);
                    String result = Base64Util.getBaseMsgForByte(ecgResult);
                    provider.addEcgHistoryData(result,picUrl,toOrigonalData[1],ptype);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case Act.Flag.ADD_ECG_PRIVER_DATA://数据上传成功
                GetToast.useString(EcgHistoryActivity.this,"数据上传成功");
                provider.requestAddScore("17", "");//添加积分
                pageNo = 1;
                loadData(Act.Flag.FLAG_REFRESH_DATA);//调用接口，进行刷新
                if(!TextUtils.isEmpty(toOrigonalData[0])){
                    try {
                        File file = new File(toOrigonalData[0]);
                        File lastFile = file.getParentFile();
                        DataCleanManager.deleteFilesByDirectory(lastFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    toOrigonalData[0] = "";
                    toOrigonalData[1] = "";
                }
                break;
        }
    }
    private void initListener() {

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.titlebar_right_tv:
                String  result = titlebar_right_tv.getText().toString();
                if(result.equals("编辑")){
                    for (int i = 0; i < ecglist.size(); i++) {
                        ecglist.get(i).setEditStatus(true);
                    }
                    titlebar_right_tv.setText("完成");
                }else if(result.equals("完成")){
                    for (int i = 0; i < ecglist.size(); i++) {
                        ecglist.get(i).setEditStatus(false);
                    }
                    titlebar_right_tv.setText("编辑");
                }
                ecgHitoryListAdapter.setEcgHitoryListAdapterDataChanged(ecglist);
                break;
            case R.id.iv_measure_ecg://去测量心电
                startMeasure();
                break;
        }
    }
    /**
     * 开启心电测量界面,调用三方arr包
     */
    private void startMeasure() {
        UserInfo userInfo = PreferenceHelper.getUser();
        InstitBean institBean = new InstitBean();
        institBean.setUserID("4525455515455555");
        int age = 0;
        String id="258";
        String KEY="ab439b80-41b9-43ce-9c38-7e93bd4b8382";
        if(!TextUtils.isEmpty(userInfo.getBirthday())){
            try {
                int year = Integer.parseInt(userInfo.getBirthday().split("-")[0]);
                age = Calendar.getInstance().get(Calendar.YEAR) - year;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //InstitBean  增加了 isShowResult字段 InstitBean.setIsShowResult(0); 1表示是需要显示分析结果 0表示不显示
        String sex = userInfo.getSex();
        if(TextUtils.isEmpty(sex)){
            institBean.setAge(1);
        }else if(sex.equals("1")){//男
            institBean.setAge(1);
        }else{//女
            institBean.setAge(0);
        }
        institBean.setSex(age);
        institBean.setIsShowResult(0);
        String rname ="";
        if(!TextUtils.isEmpty( userInfo.getRname())){
            rname =   userInfo.getRname();
        }else if(!TextUtils.isEmpty( userInfo.getNick())){
            rname =  userInfo.getNick();
        }else{
            rname = "";
        }
        institBean.setUserName(rname);
        institBean.setMechanismNumber(id);
        institBean.setMechanismPassword(KEY);
        Intent intent = new Intent();
        intent.putExtra("InstitBean", institBean);
        Class  activity =  EcgActivity.class;
        intent.setClass(EcgHistoryActivity.this, activity);
        startActivityForResult(intent, 100);
    }
    /**
     * 读取文件作为byte[]数组
     *
     * @param filePath
     * @return
     * @throws Exception
     */
    public static byte[] readStream(String filePath) throws Exception {
        FileInputStream fs = new FileInputStream(filePath);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while (-1 != (len = fs.read(buffer))) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        fs.close();
        return outStream.toByteArray();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 100) {
            //测量结果图片的本地路径
            String reportImagePath = data.getStringExtra("ReportPath");

            EcgAnalyzeResponse response = (EcgAnalyzeResponse) data.getSerializableExtra("result");

            //ivMeasuringResult.setImageBitmap(BitmapFactory.decodeFile(reportImagePath));
            // tvMeasuringResult.setText(response.getDGSResult());
            if (!response.getDGSResult().contains("请重新")) {
                try {
                    upload(reportImagePath);//先上传图片，
                    toOrigonalData [0] = reportImagePath;
                    LogUtil.i(TAG, response.toString());
                    String ecgResult = "";
                    try {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("ResultCode",response.getDGSResult());
                        jsonObject.put("HeartRate",response.getHeartRate());
                        jsonObject.put("PwaveT",response.getPwaveT());
                        jsonObject.put("QRSwaveT",response.getQRSwaveT());
                        jsonObject.put("PwaveAxis",response.getPwaveAxis());
                        jsonObject.put("RwaveAxis",response.getRwaveAxis());
                        jsonObject.put("TwaveAxis",response.getTwaveAxis());
                        jsonObject.put("PR",response.getPR());
                        jsonObject.put("QT",response.getQT());
                        jsonObject.put("QTc",response.getQTc());
                        jsonObject.put("RV5",response.getRV5());
                        jsonObject.put("SV1",response.getSV1());
                        jsonObject.put("SV2",response.getSV2());
                        jsonObject.put("RV6",response.getRV6());
                        jsonObject.put("DGSResult",response.getDGSResult());
                        jsonObject.put("NormalECG",response.getNormalECG());
                        ecgResult = jsonObject.toString();
                        toOrigonalData [1] = ecgResult;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else{
                GetToast.useString(EcgHistoryActivity.this,"解析错误");
            }

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
    /**
     * 第一次上传和重新上传
     *
     * @param
     */
    private void upload(String url) {
        upLoader.uploadImage(url);
        //upLoader.uploadImage3(url);
    }
}

